﻿
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sproc_File_CreateUpdateFile_V2]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[sproc_File_CreateUpdateFile_V2];
GO

CREATE PROCEDURE [dbo].[sproc_File_CreateUpdateFile_V2]
    @directoryId    int,
    @name           nvarchar(256),
    @size           int,
    @vpath          nvarchar(512),
    @fileId         int output
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;

IF ( @@TRANCOUNT = 0 )
BEGIN
    RAISERROR(N'This sproc must be executed within an active transaction.', 16, 1);
    RETURN -1;
END

IF ( (@fileId IS NULL) OR (@fileId <= 0) )
BEGIN
    INSERT INTO dbo.UDS_File_File (DirectoryId, [Name], [Version], [Size], VPath)
        VALUES( @directoryId, @name, 1, @size, @vpath );
    SET @fileId = @@IDENTITY;
END
ELSE
BEGIN
    UPDATE dbo.UDS_File_File
        SET
            [Name]    = @name,
            [Version] = [Version] + 1,
            [Size]    = @size,
            VPath     = @vpath,
            LastModified = getdate()
        WHERE FileId = @fileId;

    IF ( @@ROWCOUNT = 0 )
    BEGIN
        RAISERROR(N'Failed to update the specified file "%d" since it does not exist.', 16, 1, @fileId);
    END
END

END
GO

